import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getCurrentAdmin, logout, type AdminInfo, type LoginParams } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const admin = ref<AdminInfo | null>(null)
  const token = ref<string | null>(localStorage.getItem('admin_token'))
  const isLoggedIn = ref<boolean>(!!token.value)

  // 登录
  async function loginAction(params: LoginParams) {
    try {
      const response = await login(params)

      admin.value = response.admin
      token.value = response.token
      isLoggedIn.value = true

      // 保存token到localStorage
      localStorage.setItem('admin_token', response.token)

      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 获取当前管理员信息
  async function fetchCurrentAdmin() {
    try {
      const response = await getCurrentAdmin()
      admin.value = response.data
      return response.data
    } catch (error) {
      console.error('获取管理员信息失败:', error)
      // 如果获取失败，清除登录状态
      logoutAction()
      throw error
    }
  }

  // 登出
  async function logoutAction() {
    try {
      if (token.value) {
        await logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 无论请求是否成功，都清除本地状态
      admin.value = null
      token.value = null
      isLoggedIn.value = false
      localStorage.removeItem('admin_token')
    }
  }

  // 初始化时检查登录状态
  async function initAuth() {
    // 只在有token时才尝试获取用户信息，但不在这里处理错误
    // 错误处理交给路由守卫
    if (token.value && !admin.value) {
      // 这里不做任何操作，让路由守卫来处理token验证
      return
    }
  }

  return {
    admin,
    token,
    isLoggedIn,
    loginAction,
    fetchCurrentAdmin,
    logoutAction,
    initAuth
  }
})
